package com.jwiki.app.jkeeper.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.jwiki.app.jkeeper.common.data.Response;

public class ExceptionInterceptor extends SimpleMappingExceptionResolver {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionInterceptor.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception e) {
        LOGGER.error(e.getLocalizedMessage(), e);

        boolean isSendAjax = (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest"));

        if (isSendAjax) {
            // ajax
            Response data = new Response();
            data.setMessage(e.getMessage());
            // error view
            ModelAndView mv = new ModelAndView();
            mv.setView(new MappingJackson2JsonView());
            mv.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            mv.addAllObjects(data.toMap());
            return mv;
        } else {
            // redirect
            return super.doResolveException(request, response, handler, e);
        }
    }

}
